﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using WebApplication1.Repository;
using Microsoft.AspNetCore.Http;
using MongoDB.Driver;

namespace WebApplication1.Controllers;
[ApiController]
[Route("api/[controller]")]
[Authorize] // 👈 添加此特性，确保需要 JWT Token 才能访问
public class ChatController : ControllerBase
{

    private readonly ChatMessageRepository _repository;
    private readonly IMongoCollection<User> _collection;
    private readonly IMongoCollection<ChatMessage> _privateCollection;
    private readonly IMongoCollection<ChatMessage> _lobbyCollection;
    private readonly IMongoCollection<ChatMessage> _groupCollection;

    public ChatController(ChatMessageRepository repository,IMongoDatabase database)
    {
        _repository = repository;
        _collection = database.GetCollection<User>("Users");
        _lobbyCollection = database.GetCollection<ChatMessage>("LobbyMessages");
        _groupCollection = database.GetCollection<ChatMessage>("GroupMessages");
        _privateCollection = database.GetCollection<ChatMessage>("PrivateMessages");

    }

    [HttpGet("history")]
    public async Task<IActionResult> GetLobbyHistory()
    {
        // 从数据库中获取最近的 50 条消息
        var messages = await _lobbyCollection.Find(Builders<ChatMessage>.Filter.Empty)
            .SortByDescending(m => m.Timestamp)
            .Limit(50)
            .ToListAsync();

        // 返回格式化后的消息
        return Ok(messages.Select(m => new
        {
            user = m.FromUserId, // 确保字段名与 BsonElement 映射一致
            message = m.Content,
            time = m.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")
        }));
    }


    [HttpGet("private/{target}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(string), StatusCodes.Status401Unauthorized)]
    [ProducesDefaultResponseType]
    public async Task<IActionResult> GetPrivateMessages(string target)
    {
        var currentUser = User.Identity?.Name;
        if (string.IsNullOrEmpty(currentUser))
        {
            return Unauthorized("用户未登录");
        }

        var filter = Builders<ChatMessage>.Filter.Or(
            Builders<ChatMessage>.Filter.And(
                Builders<ChatMessage>.Filter.Eq(m => m.FromUserId, currentUser),
                Builders<ChatMessage>.Filter.Eq(m => m.ToUserId, target)
            ),
            Builders<ChatMessage>.Filter.And(
                Builders<ChatMessage>.Filter.Eq(m => m.FromUserId, target),
                Builders<ChatMessage>.Filter.Eq(m => m.ToUserId, currentUser)
            )
        );

        var messages = await _privateCollection.Find(filter)
            .SortBy(m => m.Timestamp)
            .ToListAsync();

        return Ok(messages.Select(m => new
        {
            user = m.FromUserId,
            message = m.Content,
            time = m.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")
        }));
    }




}